﻿using System;

using X.Common;
using E.Model;
using E.BLL;
using E.Web.UI.Page;
using E.Web.Common;

namespace E.Web
{
    public partial class Login : BasePage
    {
        private string tips;

        protected override void ShowPage()
        {
            if (ispost)
            {
                string loginid = XRequest.GetString("LoginIDTxt");
                string pwd = XRequest.GetString("PwdTxt");
                string vcode = XRequest.GetString("validateCodeTxt");

                if (!CheckForm())
                {
                    DateTime now = DateTime.Now;
                    string ip = XRequest.GetIP();

                    UserModel model = new UserModel();
                    model.LoginID = loginid;
                    model.Pwd = Utils.MD5(pwd);
                    model.LastLoginTime = now;
                    model.LastLoginIP = ip;

                    string reffer = XRequest.GetUrlReferrer();

                    ShortUserModel sum = (new UserBLL()).Login(model);
                    if (sum.ID != -1)
                    {
                        model.ID = sum.ID;
                        (new UserBLL()).InsertLoginHistory(model);
                        WebCommon.WriteUserCookie(sum.ID.ToString(), sum.UserName, sum.AreaID.ToString(), sum.IsPublic ? 1 : 0);
                        //ExecuteJS("alert('登录成功'); window.top.location = '" + reffer + "';");
                        //ExecuteJS("window.top.location = '" + reffer + "';");
                        ExecuteJS("alert('登录成功'); window.top.location.replace('/training/frames/Index.aspx');");
                    }
                    else
                    {
                        ExecuteJS("alert('用户名与密码不符'); window.top.location = '/Default.aspx';");
                    }
                }
                else
                {
                    ExecuteJS("alert('" + tips + "'); window.top.location = '/Default.aspx';");
                }
            }
        }

        private bool CheckForm()
        {
            bool isWrong = false;
            if (XRequest.GetString("LoginIDTxt").Trim().Equals("") || XRequest.GetString("PwdTxt").Trim().Equals(""))
            {
                tips = "用户名与密码不符";
                isWrong = true;
            }
            else if (XRequest.GetString("validateCodeTxt").Trim().Equals("") || XRequest.GetString("validateCodeTxt").Trim().ToLower() != Utils.GetCookie("vcode"))
            {
                tips = "验证码错误";
                isWrong = true;
            }
            return isWrong;
        }
    }
}
